﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Repository;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Cxuu.Service
{
    [AppService]
    public class AdminUserDeptService
    {
        private readonly AdminUserDeptRepository _adminUserDept;
        private readonly AdminUserRepository _adminUser;
        private readonly ICacheManager _cacheManager;
        private readonly string cacheKey;
        public AdminUserDeptService(ICacheManager cacheManager, AdminUserDeptRepository adminUserDeptRepository, AdminUserRepository adminUser)
        {
            _adminUserDept = adminUserDeptRepository;
            _cacheManager = cacheManager;
            cacheKey = CacheConst.CACHE_KEY_ADMINDEPTCATE;
            _adminUser = adminUser;
        }

        /// <summary>
        /// 全部列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<AdminUserDept>> GetAllAsync()
        {
            List<AdminUserDept> cate = _cacheManager.Get<List<AdminUserDept>>(cacheKey);
            if (cate == null)
            {
                cate = await _adminUserDept.GetAllListAsync("Id desc");
                _cacheManager.Set(cacheKey, cate, TimeSpan.FromDays(10));
            }
            return cate;
        }

        public async Task<AdminUserDept> GetInfo(int id)
        {
            List<AdminUserDept> userDepts = await GetAllAsync();
            return userDepts.FirstOrDefault(a => a.Id == id);
        }


        #region 获取所有下级

        /// <summary>
        /// 获取当前部门及子部门ID值字符串
        /// </summary>
        /// <param name="Pid"></param>
        /// <returns></returns>
        public async Task<List<int>> GetDeptAndSonIdsAsync(int Pid)
        {
            List<AdminUserDept> userDepts = await GetAllAsync();
            var query = userDepts.Where(p => p.Id == Pid).ToList();
            var list2 = query.Concat(GetSonList(userDepts, Pid));
            List<int> ids = list2.Select(o => o.Id).ToList();
            //ids.Add(Pid);//包含自己
            return ids;
        }

        public static IEnumerable<AdminUserDept> GetSonList(IList<AdminUserDept> list, int Pid)
        {
            var query = list.Where(p => p.Pid == Pid).ToList();
            return query.ToList().Concat(query.ToList().SelectMany(t => GetSonList(list, t.Id)));
        }
        #endregion

        #region 获取所有上级
        public static IEnumerable<AdminUserDept> GetFatherList(IList<AdminUserDept> list, int Id)
        {
            var query = list.Where(p => p.Id == Id).ToList();
            return query.ToList().Concat(query.ToList().SelectMany(t => GetFatherList(list, t.Pid)));
        }
        #endregion

        public async Task<object> InsertAsync(AdminUserDept adminUserDept)
        {
            _cacheManager.Remove(cacheKey);
            return await _adminUserDept.InsertAsync(adminUserDept);
        }

        public async Task<int> UpdateAsync(AdminUserDept adminUserDept)
        {
            _cacheManager.Remove(cacheKey);
            return await _adminUserDept.UpdateAsync(adminUserDept);
        }
        public async Task<int> UpdateAdminUserDeptCateRoleAsync(AdminUserDeptCateRole adminUserDeptCate)
        {
            AdminUserDept adminUserDept = await GetInfo(adminUserDeptCate.Id);

            if (adminUserDeptCate.ArticleCateRole != null)
                adminUserDept.ArticleCateRole = adminUserDeptCate.ArticleCateRole;
            if (adminUserDeptCate.ContentCateRole != null)
                adminUserDept.ContentCateRole = adminUserDeptCate.ContentCateRole;

            if (0 < await _adminUserDept.UpdateAsync(adminUserDept))
            {
                _cacheManager.Remove(cacheKey);
                return 1;
            }
            return 0;
        }
        public async Task<int> DeleteByPriKeyAsync(int id)
        {
            if (await _adminUser.GetUserByDeptIdAsync(id))
                return -1;
            _cacheManager.Remove(cacheKey);
            return await _adminUserDept.DeleteByPriKeyAsync(id);
        }


        /// <summary>
        /// 查询栏目列表并转换
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<SelectListItem>> GetDeptSelectListItemsAsync()
        {
            List<AdminUserDept> cates = await GetAllAsync();
            return cates.AsSelectListItems();//导出带 select标签样式的数据
        }
        public async Task<IEnumerable<ViewAdminUserDept>> GetUserDeptListAsync()
        {
            List<AdminUserDept> cates = await GetAllAsync();
            return cates.AsCateListItems();//导出带 所有栏目封装数据
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<ViewAdminUserDept>> GetAdminUserDepts()
        {
            return await GetUserDepts(0, await GetAllAsync());
        }


        /// <summary>
        /// 递归栏目树
        /// </summary>
        /// <param name="pid">父级Id</param>
        /// <param name="cates">数据源</param>
        /// <returns></returns>
        private async Task<List<ViewAdminUserDept>> GetUserDepts(int pid, List<AdminUserDept> depts = null)
        {
            var parent = depts.Where(P => P.Pid == pid);
            List<ViewAdminUserDept> lists = new();
            foreach (var item in parent)
            {
                ViewAdminUserDept Childer = new()
                {
                    Id = item.Id,
                    DeptName = item.DeptName,
                    OrderNum = item.OrderNum,
                    Remark = item.Remark,
                    GreatTime = item.GreatTime,
                };
                Childer.Children = await GetSon(Childer, depts);
                if (Childer.Children != null)
                {
                    Childer.HaveChild = true;
                    Childer.Open = true;
                }
                lists.Add(Childer);
            }
            async Task<List<ViewAdminUserDept>> GetSon(ViewAdminUserDept cates, List<AdminUserDept> sonCates = null)
            {
                if (!sonCates.Exists(x => x.Pid == cates.Id))
                {
                    return null;
                }
                else
                {
                    return await GetUserDepts(cates.Id, sonCates);
                }
            }
            return lists.OrderBy(o => o.OrderNum).ThenBy(o => o.Id).ToList();
        }
    }
}
